package com.university.evaluation.service.impl;
import com.university.evaluation.entity.User;
import com.university.evaluation.entity.Role;
import com.university.evaluation.mapper.RoleMapper;
import com.university.evaluation.service.UserService; // [NEW] 推荐注入Service而不是Mapper
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    // [MODIFIED] 推荐注入 Service 层，而不是直接操作 Mapper
    @Autowired
    private UserService userService;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // Spring Security 传递过来的 "username" 参数，实际上是用户在登录框输入的“学号”
        log.info("UserDetailsServiceImpl: 正在根据登录标识符 '{}' 加载用户...", username);

        // [MODIFIED] 核心修正：调用 findByStudentId 方法，使用学号进行查询
        User user = userService.findByStudentId(username);

        if (user == null) {
            log.warn("UserDetailsServiceImpl: 数据库中未找到学号为 '{}' 的用户。", username);
            throw new UsernameNotFoundException("学号或密码错误");
        }

        log.info("UserDetailsServiceImpl: 成功找到用户, 学号: {}, 准备加载权限。", user.getStudentId());

        // 构建用户的权限列表
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (user.getRoleId() != null) {
            Role role = roleMapper.selectById(user.getRoleId());
            if (role != null && role.getRoleKey() != null && !role.getRoleKey().trim().isEmpty()) {
                String roleKey = "ROLE_" + role.getRoleKey().toUpperCase();
                authorities.add(new SimpleGrantedAuthority(roleKey));
                log.info("为用户 '{}' 添加了权限: {}", user.getStudentId(), roleKey);
            }
        }

        // 返回Spring Security需要的UserDetails对象
        return new org.springframework.security.core.userdetails.User(
                user.getStudentId(), // 使用唯一的学号作为 principal (身份标识)
                user.getPassword(),
                user.getStatus() != null && user.getStatus() == 1,
                true,
                true,
                true,
                authorities
        );
    }
}